<template>
    <div class="toolbar-com" :style="{width: step === 1 ? '460px' : '690px'}">
        <div class="tool">
            <div class="left" :style="{right: showDraw ? '23px' : '-200px'}">
                <div :class="['wrapper', {wrapperActive: el.active, wrapperDisabled: el.disabled}]" v-for="el in toolbarList" :key="el.code" :title="el.label" @click="el.onClick(el)">
                    <span :class="['icon', `icon_${el.code}`, {disabled: el.disabled}]"></span>
                </div>
                <span class="triangle"></span>
            </div>
            <span class="right" @click="handleDraw">绘制</span>
        </div>

        <InfoCom v-show="step === 1" :imgFileAreas1="imgFileAreas1" :imgFileAreas2="imgFileAreas2" @initInfoCom="initInfoCom" @changeTab="changeTab" @changeType="changeType" @removeTab="removeTab" @next="handleNext" />
        <WordCom v-show="step === 2" @back="handleBack" :httpUrl="httpUrl" :realPath="realPath" />
    </div>
</template>

<script>
import { mapGetters } from 'vuex';
import TabCom from './TabCom.vue';
import InfoCom from './InfoCom.vue';
import WordCom from './WordCom.vue';

export default {
    name: 'ToolbarCom',
    components: {
        TabCom,
        InfoCom,
        WordCom,
    },
    props: {
        mapGis: {
            type: Object,
            default: () => {},
        },
    },
    computed: {
        ...mapGetters([
            'getMapId',
            'getDrawLayerId',
        ]),
    },
    data() {
        return {
            showDraw: true,
            toolbarList: [
                {
                    label: '折线绘制',
                    code: 'line',
                    active: false,
                    disabled: false,
                    onClick: (item) => {
                        this.clickLine(item);
                    }
                },
                {
                    label: '基于行政区编辑',
                    code: 'edit',
                    active: false,
                    disabled: true,
                    onClick: (item) => {
                        this.clickEdit(item);
                    }
                },
                {
                    label: '删除单个行政区',
                    code: 'delete1',
                    active: false,
                    disabled: true,
                    onClick: (item) => {
                        this.clickDelete1(item);
                    }
                },
                {
                    label: '删除',
                    code: 'deleteAll',
                    active: false,
                    disabled: true,
                    onClick: (item) => {
                        this.clickDeleteAll(item);
                    }
                }
            ],
            step: 1,
            httpUrl: '',
            realPath: '',
            currentLayerCfg: {},
            imgFileAreas1: [],
            imgFileAreas2: [],
            editEvent: null,
            erasureEvent: null,
            userId: '',
            warnType: '',
            areaCode: [],
        }
    },
    mounted() {
        let { areaCode = ''} = this.$route.query;
        this.areaCode = areaCode.split(',');
        let index = this.areaCode.findIndex(el => el === '120101');
        if (index !== -1) {
            this.areaCode.splice(index, 1, '100107');
        }
    },
    methods: {
        async initInfoCom(areacodes) {
            console.log('areacodes======>', JSON.stringify(areacodes));
            let currentLayerCfg = JSON.parse(JSON.stringify(this.currentLayerCfg));
            let geoDatas = GIS.TJPlugin.getInfoByAreacode(this.getMapId, areacodes); //根据编码获取对应数据
            let option = {//设置样式、层级信息等
                style: {
                    strokeStyle: currentLayerCfg.strokeStyle, //设置边界线条颜色
                    lineWidth: 2, //设置边界线宽
                    fillStyle: currentLayerCfg.fillStyle //设置填充颜色
                },
                zIndex: 2
            }
            GIS.Graphic.showPolygon(this.getMapId, currentLayerCfg.fallZoneLayerId, geoDatas, option); //显示
            if (currentLayerCfg.type === 'RAT') {
                this.imgFileAreas1 = geoDatas.map(el => el.attributes);
            } else {
                this.imgFileAreas2 = geoDatas.map(el => el.attributes);
            }
        },
        handleDraw() {
            this.showDraw = !this.showDraw;
        },
        clickLine(item) {
            if (item.disabled) return;
            item.active = !item.active;
            if (item.active) {
                let drawStyleObj = {
                    stroke: 'rgb(255,0,0,1)', 
                    fill: 'rgb(255,255,0,0.2)', 
                    'stroke-opacity': 1, 
                    'fill-opacity': 1, 
                    'stroke-width': 2 
                };
                GIS.Draw.startDraw(
                    this.getMapId, 
                    this.currentLayerCfg.drawLayerId,
                    'bezierPolygon', 
                    null, 
                    drawStyleObj, 
                    graphic => {
                        if (mapObj[this.getMapId].getLayer(this.currentLayerCfg.drawLayerId)) mapObj[this.getMapId].getLayer(this.currentLayerCfg.drawLayerId).clear();//清空已绘制图案

                        let sourceData = {
                            //graphic.geometry结构如：[[[x1,y1],[x2,y2]....[xn,yn]]]
                            graphic: { geometry: graphic.geometry },//绘图返回的图形数据，用来进行计算
                            type: 'town',//获取行政区域级别，'district'为区县，town为乡镇（预留接口，目前仅支持区县）
                            style: {//行政区域显示样式
                                strokeStyle: this.currentLayerCfg.strokeStyle,//设置边界线条颜色
                                lineWidth: 2, //设置边界线宽
                                fillStyle: this.currentLayerCfg.fillStyle //设置填充颜色
                            },
                            zIndex: 2//行政区域显示层级
                        }
                        //返回数据newData为框选后新添加的行政区域名称数组
                        let newData = GIS.TJPlugin.fillArea(this.getMapId, this.currentLayerCfg.fallZoneLayerId, sourceData);
                        if (this.currentLayerCfg.type === 'RAT') {
                            this.imgFileAreas1 = newData.all.xian;
                        } else {
                            this.imgFileAreas2 = newData.all.xian;
                        }
                        console.log('newData======>', newData);
                    }
                );
            } else {
                GIS.Draw.endDraw(this.getMapId, this.currentLayerCfg.drawLayerId);
                this.toolbarList.forEach(el => el.disabled = el.code === 'line');
            }
        },
        clickEdit(item) {
            if (item.disabled) return;
            item.active = !item.active;
            if (item.active) {
                this.toolbarList.find(el => el.code === 'delete1').active = false;
                this.erasureEvent && this.mapGis.getLayer(this.currentLayerCfg.fallZoneLayerId).off(this.erasureEvent);

                this.editEvent = this.mapGis.on('click', e => {//开启图层点击事件，返回事件对象
                    let sourceData = {
                        graphic: [e.mapX, e.mapY],//绘图返回的图形数据，用来进行计算
                        type: 'district',//获取行政区域级别，'district'为区县，town为乡镇（预留接口，目前仅支持区县）
                        style: {//行政区域显示样式
                            strokeStyle: this.currentLayerCfg.strokeStyle,//设置边界线条颜色
                            lineWidth: 2, //设置边界线宽
                            fillStyle: this.currentLayerCfg.fillStyle //设置填充颜色
                        },
                        zIndex: 2 //行政区域显示层级
                    }
                    //返回数据newData为框选后新添加的行政区域名称数组，为保持一致，与框选返回格式相同
                    let newData = GIS.TJPlugin.fillAreaByPoint(this.getMapId, this.currentLayerCfg.fallZoneLayerId, sourceData);
                    if (this.currentLayerCfg.type === 'RAT') {
                        this.imgFileAreas1 = newData.all.xian;
                    } else {
                        this.imgFileAreas2 = newData.all.xian;
                    }
                    console.log('newData======>', newData);
                })
            } else {
                this.mapGis.off(this.editEvent); //关闭地图基于行政区编辑事件
            }
        },
        clickDelete1(item) {
            if (item.disabled) return;
            item.active = !item.active;
            if (item.active) {
                this.toolbarList.find(el => el.code === 'edit').active = false;
                this.editEvent && this.mapGis.off(this.editEvent);

                let layer = this.mapGis.getLayer(this.currentLayerCfg.fallZoneLayerId); //获取图层对象
                this.erasureEvent = layer.on('click', e => { //开启图层点击事件，返回事件对象
                    layer.remove(e.graphic); //移除点击得到的图形对象
                    this.mapGis.refresh(); //地图刷新显示
                    if (this.currentLayerCfg.type === 'RAT') {
                        this.imgFileAreas1 = this.imgFileAreas1.filter(el => el.areacode != e.graphic.attributes.areacode);
                    } else {    
                        this.imgFileAreas2 = this.imgFileAreas2.filter(el => el.areacode != e.graphic.attributes.areacode);
                    }
                });
            } else {
                this.mapGis.getLayer(this.currentLayerCfg.fallZoneLayerId).off(this.erasureEvent); //关闭地图删除事件
            }
        },
        clickDeleteAll(item) {
            if (item.disabled) return;
            this.clearAll();
        },
        changeType(item, graphicIds) {
            this.currentLayerCfg = item;
            let newStyle = {
                strokeStyle: this.currentLayerCfg.strokeStyle, //设置边界线条颜色
                fillStyle: this.currentLayerCfg.fillStyle //设置填充颜色
            }
            let res = GIS.TJPlugin.changeAreaStyle(this.getMapId, this.currentLayerCfg.fallZoneLayerId, graphicIds.map(el => el.areacode), newStyle)//新添加方法，用来修改指定code图形的样式
            if (this.currentLayerCfg.type === 'RAT') {
                this.imgFileAreas2 = [];
                this.imgFileAreas1 = JSON.parse(JSON.stringify(graphicIds));
            } else {
                this.imgFileAreas1 = [];
                this.imgFileAreas2 = JSON.parse(JSON.stringify(graphicIds));
            }
        },
        changeTab(item) {
            this.reset();
            GIS.LayerControll.showControll(this.getMapId, [this.currentLayerCfg.drawLayerId, this.currentLayerCfg.fallZoneLayerId], false);
            this.currentLayerCfg = item;
            GIS.LayerControll.showControll(this.getMapId, [this.currentLayerCfg.drawLayerId, this.currentLayerCfg.fallZoneLayerId], true);
            console.log('changeTab this.currentLayerCfg======>', this.currentLayerCfg);
        },
        removeTab(item, currentItem) {
            this.toolbarList.forEach(el => {
                el.active = false;
                el.disabled = el.code != 'line';
            });
            GIS.Draw.endDraw(this.getMapId, item.drawLayerId);
            this.editEvent && this.mapGis.off(this.editEvent);
            this.erasureEvent && this.mapGis.getLayer(item.fallZoneLayerId).off(this.erasureEvent);
            GIS.LayerControll.deleteLayer(this.getMapId, [item.drawLayerId, item.fallZoneLayerId]);
            if (item.type === 'RAT') {
                this.imgFileAreas1 = [];
            } else {
                this.imgFileAreas2 = [];
            }

            this.currentLayerCfg = currentItem;
            GIS.LayerControll.showControll(this.getMapId, [this.currentLayerCfg.drawLayerId, this.currentLayerCfg.fallZoneLayerId], true);
        },
        handleNext(data) {
            this.httpUrl = data.httpUrl;
            this.realPath = data.realPath;
            this.step = 2;
        },
        handleBack() {
            this.step = 1;
        },
        clearAll() {
            this.reset();
            GIS.LayerControll.deleteLayer(this.getMapId, [this.currentLayerCfg.drawLayerId, this.currentLayerCfg.fallZoneLayerId]);
            if (this.currentLayerCfg.type === 'RAT') {
                this.imgFileAreas1 = [];
            } else {
                this.imgFileAreas2 = [];
            }
        },
        reset() {
            this.toolbarList.forEach(el => {
                el.active = false;
                el.disabled = el.code != 'line';
            });
            GIS.Draw.endDraw(this.getMapId, this.currentLayerCfg.drawLayerId);
            this.editEvent && this.mapGis.off(this.editEvent);
            this.erasureEvent && this.mapGis.getLayer(this.currentLayerCfg.fallZoneLayerId).off(this.erasureEvent);
        }
    }
}
</script>

<style lang="less" scoped>
.toolbar-com {
    position: absolute;
    top: 0;
    right: 0;
    z-index: 10;
    display: flex;
    width: 460px;
    height: 100%;
    box-shadow: rgba(0, 0, 0, 0.2) 0px 8px 10px -5px, rgba(0, 0, 0, 0.14) 0px 16px 24px 2px, rgba(0, 0, 0, 0.12) 0px 6px 30px 5px;

    .tool {
        position: absolute;
        top: 10px;
        left: -218px;
        z-index: 20;
        display: flex;
        width: 208px;
        height: 35px;
        overflow: hidden;

        .left {
            position: absolute;
            right: 23px;
            top: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 5px;
            border: 1px solid #5f9ce5;
            border-right: none;
            padding-right: 10px;
            width: 185px;
            height: 35px;
            background-color: #ffffff;
            transition: right 0.3s ease;

            .wrapper {
                display: flex;
                justify-content: center;
                align-items: center;
                width: 40px;
                height: 33px;
                cursor: pointer;

                &:hover {
                    background-color: #5f9ce5;
                }

                &.wrapperActive {
                    background-color: #5f9ce5;
                }

                &.wrapperDisabled {
                    background-color: #ffffff;
                    cursor: not-allowed;
                }

                .icon {
                    width: 28px;
                    height: 24px;
                    background-color: #5f9ce5;

                    &.icon_line {
                        background: url('@/assets/images/toolbar/line.png') no-repeat center center / 100% 100%;
                    }

                    &.icon_line.disabled {
                        background: url('@/assets/images/toolbar/line_disabled.png') no-repeat center center / 100% 100%;
                    }

                    &.icon_edit {
                        background: url('@/assets/images/toolbar/edit.png') no-repeat center center / 100% 100%;
                    }

                    &.icon_edit.disabled {
                        background: url('@/assets/images/toolbar/edit_disabled.png') no-repeat center center / 100% 100%;
                    }

                    &.icon_delete1 {
                        background: url('@/assets/images/toolbar/delete1.png') no-repeat center center / 100% 100%;
                    }

                    &.icon_delete1.disabled {
                        background: url('@/assets/images/toolbar/delete1_disabled.png') no-repeat center center / 100% 100%;
                    }

                    &.icon_deleteAll {
                        background: url('@/assets/images/toolbar/deleteAll.png') no-repeat center center / 100% 100%;
                    }

                    &.icon_deleteAll.disabled {
                        background: url('@/assets/images/toolbar/deleteAll_disabled.png') no-repeat center center / 100% 100%;
                    }
                }
            }

            .triangle {
                position: absolute;
                right: 0;
                top: 50%;
                transform: translateY(-50%);
                width: 0;
                height: 0;
                border-top: 10px solid transparent;
                border-bottom: 10px solid transparent;
                border-right: 10px solid #5f9ce5;
            }
        }

        .right {
            position: absolute;
            right: 0;
            top: 0;
            padding: 4px 0 0 5px;
            width: 23px;
            height: 35px;
            font-size: 12px;
            color: #ffffff;
            background-color: #5f9ce5;
            cursor: pointer;
        }
    }
}
</style>
